import store from '../store'
import router from '../router'
import message from './message'
let timeOut = null
let roleList = [
  'ROLE_MJ_HQ_OPERATIONS', // '美居总部运营'
  'ROLE_MJ_CITY_OPERATIONS', // '美居城市公司运营'
  'ROLE_MJ_CITY_ADMIN', // '美居城市管理员'
  'ROLE_MJ_SUPPLIER_ADMIN' // '美居商户管理'
]

export function getCookie (name) {
  let reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
  // let daa = 'expires_in=604800; scope=r-user%20123; access_token=4b7d5092-3c11-4a39-9283-e640db167732; refresh_token=ff10c380-7d31-45ef-b292-4042cd1afdbb'
  let arr = document.cookie.match(reg)
  // debugger
  if (arr) {
    return arr[2]
  } else {
    return null
  }
}

export function setExpries () { // 2小时不操作自动退出
  let expries = 2 * 60 * 60 * 1000
  clearTimeout(timeOut)
  timeOut = setTimeout(() => {
    loginOut()
  }, expries)
}

export function delCookie (name, token) {
  let naw = new Date().getTime() - 1000 * 3600 * 24 * 7
  let now = new Date(naw)
  document.cookie = name + '=' + token + ';expires=' + now.toGMTString() + ';domain=.4009515151.com;path=/'
}

export async function loginOut () { // 登出
    await store.dispatch('delToken')
    await store.dispatch('delPermissionRouter')
    await pushLogin()
    // setTimeout(()=>{
    //   window.location.reload()
    // }, 200)
    // await reloadAction()
    // window.location.reload()
}

export async function pushLogin(){
  await router.push({
    path: '/login'
  })
  // window.location.reload()
}

// export async function reloadAction(){
//   window.location.reload()
// }

export function regRole () { // 登入完后验证是否有后台角色
  let userInfo = store.getters['user/getUserInfo']
  if (userInfo.role_code) {
    let status = false
    userInfo.role_code.forEach((item) => {
      if (roleList.includes(item)) {
        status = true
      }
    })
    if (!status) {
      message.warning('暂无角色')
      loginOut()
    }
  } else {
    loginOut()
  }
}
